"""
测试运行脚本
用于运行所有测试并生成报告
"""
import os
import sys
import subprocess
import argparse
from datetime import datetime

def run_tests(test_type="all", coverage=False):
    """运行测试"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(os.path.dirname(base_dir))  # 切换到项目根目录
    
    # 构建测试命令
    command = ["python", "-m", "pytest", "tests/", "-v"]
    
    if test_type == "unit":
        command.append("-m")
        command.append("unit")
    elif test_type == "integration":
        command.append("-m")
        command.append("integration")
    
    if coverage:
        command.extend([
            "--cov=app",
            "--cov-report=html",
            "--cov-report=term-missing"
        ])
    
    # 添加测试报告输出
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    report_file = f"test_report_{timestamp}.html"
    command.extend([
        "--html=reports/" + report_file,
        "--self-contained-html"
    ])
    
    # 确保报告目录存在
    os.makedirs("reports", exist_ok=True)
    
    print(f"运行测试命令: {' '.join(command)}")
    
    try:
        result = subprocess.run(command, check=True)
        print(f"\n✅ 测试完成！报告已保存到: reports/{report_file}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"\n❌ 测试失败，退出代码: {e.returncode}")
        return False

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="运行测试套件")
    parser.add_argument(
        "--type", 
        choices=["all", "unit", "integration"], 
        default="all",
        help="测试类型: all(所有), unit(单元测试), integration(集成测试)"
    )
    parser.add_argument(
        "--coverage", 
        action="store_true",
        help="生成代码覆盖率报告"
    )
    
    args = parser.parse_args()
    
    print("开始运行测试...")
    success = run_tests(args.type, args.coverage)
    
    if success:
        print("\n✅ 所有测试通过")
        sys.exit(0)
    else:
        print("\n❌ 测试失败")
        sys.exit(1)

if __name__ == '__main__':
    main()